import React, { Component } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Input, Tree, Table } from 'antd';
import _ from 'lodash';
import styles from './index.less';
import * as apis from '@/services/SystemMgr';
import Mpagination from '../../../components/Mpagination';

const { Search } = Input;

@connect(state => ({
  systemManageItems: state.SystemManageItems,
}))
export default class ChoiceUser extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expandedKeys: ['00000000'],
      autoExpandParent: true,
      selectedRowKeys: [],
      params: {
        current: '1',
        departmentnumber: '',
        pageSize: '20',
        usercn: '',
      },
      total: '0',
      pages: '0',
      loading: true,
      // 用户
      userColumns: [
        {
          title: '序号',
          dataIndex: 'key',
          align: 'center',
          width: 50,
        },
        {
          title: '用户账号',
          dataIndex: 'accountNumber',
          align: 'center',
          width: 100,
        },
        {
          title: '用户名称',
          dataIndex: 'userName',
          align: 'center',
          width: 100,
        },
        {
          title: '岗位名称',
          dataIndex: 'sentryName',
          align: 'center',
          width: 100,
        },
        {
          title: '登陆名',
          dataIndex: 'landName',
          align: 'center',
          width: 90,
        },
        {
          title: '用户类型',
          dataIndex: 'userType',
          align: 'center',
          width: 100,
        },
        {
          title: '手机',
          dataIndex: 'phone',
          align: 'center',
          width: 140,
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          align: 'center',
        },
        {
          title: '部门编码',
          dataIndex: 'departmentCode',
          align: 'center',
          width: 100,
        },
        {
          title: '用户性别',
          dataIndex: 'gender',
          align: 'center',
          width: 80,
        },
      ],
      userData: [],
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'SystemManageItems/init',
      payload: {},
    });
    this.getUsers(this.state.params);
  }

  componentWillReceiveProps(nextProps) {
    this.setState({
      expandedKeys: nextProps.systemManageItems.expandedKeys,
    });
  }

  // 获取用户数据
  async getUsers(params) {
    const self = this;
    this.setState({ userData: [] });
    const getUserData = await apis.getUserPageListUsingGET({ params });
    if (getUserData.code === 1) {
      const arr = [];
      getUserData.data.list.map((item, index) => {
        const obj = {
          key: getUserData.data.pageSize * (getUserData.data.current - 1) + index + 1,
          accountNumber: item.username,
          userName: item.usercn,
          sentryName: item.jobname,
          landName: item.alias,
          userType: item.usertype,
          phone: item.mobile,
          email: item.mail,
          departmentCode: item.departmentnumber,
          gender: item.genderId,
        };
        arr.push(obj);
        return arr;
      });
      this.setState({
        userData: arr,
        total: getUserData.data.total,
        pages: getUserData.data.pages,
        loading: false,
        params: {
          current: getUserData.data.current,
          departmentnumber: self.state.params.departmentnumber,
          pageSize: getUserData.data.pageSize,
          usercn: self.state.params.usercn,
        },
      });
    }
  }

  // 分页切换
  handlePaginationChange = (current, pageSize) => {
    let { params } = this.props;
    params = {
      current,
      pageSize,
      departmentnumber: this.state.params.departmentnumber,
      usercn: this.state.params.usercn,
    };
    this.setState({
      params,
    });
    this.getUsers(params);
  };

  // 修改每页参数
  onShowSizeChange = (current, pageSize) => {
    this.handlePaginationChange(current, pageSize);
  };

  // 点击组织架构树获取部门id
  clickTreeNode = selectedKeys => {
    const rel = this;
    selectedKeys.forEach(item => {
      const params = {
        current: '1',
        departmentnumber: item,
        pageSize: rel.state.params.pageSize,
        usercn: rel.state.params.usercn,
      };
      this.setState({
        params,
      });
      this.getUsers(params);
    });
  };

  handleSearchUser = value => {
    const { params } = this.state;
    params.usercn = value;
    this.getUsers({
      current: '1',
      departmentnumber: params.departmentnumber,
      pageSize: params.pageSize,
      usercn: value,
    });
    this.setState({ params });
  };

  // 搜索组织树
  searchOrgTree = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'SystemManageItems/searchOrgTree',
      payload: value,
    });
    this.setState({
      // expandedKeys: ['56569342438', '99174100492'],
      autoExpandParent: true,
    });
  };

  // 监听选中的岗位，并获取选中的id
  onSelectChange = selectedRowKeys => {
    this.props.getUserIds(selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  // 树的展开收起
  handleTreeOnExpand = expandedKeys => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  render() {
    const { total, pages, loading, selectedRowKeys, expandedKeys, autoExpandParent } = this.state;
    const { systemManageItems } = this.props;
    const tableHeight = document.body.clientHeight - 205;
    const rowSelection = {
      onChange: this.onSelectChange,
      columnWidth: 40,
      fixed: true,
      selectedRowKeys,
    };

    return (
      <div className={styles.ChoiceUser}>
        <Row>
          <Col span={5}>
            <div className="title">组织架构</div>
            <Card>
              <Search placeholder="请输入组织名搜索" onSearch={this.searchOrgTree} />
              <Tree
                onExpand={this.handleTreeOnExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                onSelect={this.clickTreeNode}
                treeData={systemManageItems.orgTree}
                defaultSelectedKeys={expandedKeys}
              />
            </Card>
          </Col>
          <Col span={19}>
            <div className="Tables">
              <Search
                style={{ width: 200, marginBottom: 2 }}
                size="small"
                onSearch={this.handleSearchUser}
                placeholder="请输入名称搜索"
              />
              <Table
                rowKey="accountNumber"
                rowSelection={rowSelection}
                columns={this.state.userColumns}
                dataSource={this.state.userData}
                bordered
                scroll={{ x: 1100, y: tableHeight }}
                pagination={false}
                size="small"
                loading={loading}
              />
            </div>
            <Mpagination
              total={total}
              pageSize={this.state.params.pageSize}
              current={this.state.params.current}
              pages={pages}
              handlePaginationChange={this.handlePaginationChange}
              onShowSizeChange={(current, pageSize) => this.onShowSizeChange(current, pageSize)}
              model={<span>当前选中{selectedRowKeys.length}条</span>}
            />
          </Col>
        </Row>
      </div>
    );
  }
}
